package im.engure.common.client.http;

import im.engure.common.protocol.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpClient {

    public static String sendHttpRequest(String hostName, Integer port, Invocation invocation) {

        try {
            URL url = new URL("http", hostName, port, "/");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            ObjectOutputStream os = new ObjectOutputStream(connection.getOutputStream());
            os.writeObject(invocation);
            os.flush();
            os.close();

            return IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8);

        } catch (Exception e) {
            e.printStackTrace();
            return "发送请求失败, " + e.getMessage();
        }

    }

}
